package com.mouse.authorization;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.ldap.core.support.SimpleDirContextAuthenticationStrategy;
import org.springframework.security.authentication.encoding.LdapShaPasswordEncoder;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.ldap.DefaultSpringSecurityContextSource;

import java.util.Arrays;
import java.util.Hashtable;

/**
 * Created by cwx183898 on 2017/8/3.
 */
@Configuration
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {

    @Value("${ldap.domain.manager}")
    private String manager;

    @Value("${ldap.domain.password}")
    private String password;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                //免验证地址
                .authorizeRequests().antMatchers("/", "/index.html", "/**/*.js", "/**/*.css", "/**/*.gif", "/**/*.png", "/**/*.jpg").permitAll()
                .anyRequest().authenticated()
                //登录
                .and()
                .formLogin().loginPage("/login").failureForwardUrl("/login").defaultSuccessUrl("/").permitAll()
                //注销
                .and()
                .logout().logoutSuccessUrl("/").permitAll();
        ;
    }


    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.ldapAuthentication()
                // .userDnPatterns("cn=*WX183898,ou=PartnerUsers")
                .userSearchFilter("(samaccountname={0})")
                .contextSource(contextSource());
    }

    @Bean
    public DefaultSpringSecurityContextSource contextSource() {
        DefaultSpringSecurityContextSource cs = new DefaultSpringSecurityContextSource("ldap://lggad05-dc/dc=china,dc=huawei,dc=com");
        cs.setUserDn(manager + "@china.huawei.com");
        cs.setPassword(password);
        return cs;
    }

}